<template>
  <div class="view-fill">
    <div
      v-if="
        !purchAppDetailinfo.visible &&
        !modifyInfo.visible &&
        !summaryDetailInfo.visible &&
        !templateModifyInfo.visible
      "
      class="app-container-flex"
    >
      <NewFullScreen
        v-model="showDialog"
        title="采购单明细"
        :needOperateAffair="true"
        :operateAffairData="affairTableInfo"
        :needReturn="!$route.query.processInstanceId"
        @returnBack="returnBack"
      >
        <template v-slot:full-button>
          <el-button
            v-if="
              $permission('purchOrder:update') &&
              (infoList.data.status === 1 || infoList.data.status === 5)
            "
            @click="update"
            >修改</el-button
          >
          <PopoverPrint
            ref="popoverShow"
            v-model:popoverVisible="popoverVisible"
            :canPrint="canPrint"
            :templateArr="templateArr"
            @tempClick="tempClick"
            @print="print"
          ></PopoverPrint>
          <el-button v-if="canExcel" @click="exportExcel">导出excel</el-button>
          <el-button v-if="canRevoke" @click="handelMethodRequest('revoke')"
            >撤回
          </el-button>
          <el-button
            v-if="canCancelAudit"
            @click="handelMethodRequest('cancelCheck')"
            >销审
          </el-button>
          <el-button v-if="canRatify" @click="handelMethodRequest('approved')"
            >批准
          </el-button>
          <el-button v-if="canBreak" @click="handelMethodRequest('stop')"
            >中止
          </el-button>
          <el-button v-if="canSubmit" @click="handelMethodRequest('submit')"
            >提交
          </el-button>
          <el-button v-if="canReject" @click="handelMethodRequest('reject')"
            >驳回</el-button
          >
          <el-button v-if="canRefuse" @click="handelMethodRequest('refuse')"
            >拒绝</el-button
          >
          <el-button v-if="canSplit" @click="handelMethodRequest('split')"
            >拆单</el-button
          >
          <el-button v-if="canDoPurch" @click="handelMethodRequest('doPurch')"
            >采购</el-button
          >
          <el-button
            v-if="
              $permission('purchOrder:saveCopeTemplat') &&
              infoList.data.status !== 2 &&
              infoList.data.status !== 18
            "
            @click="saveCopeTemplate()"
            >另存为模板</el-button
          >
          <el-button
            v-if="
              $permission('purchOrder:copy') &&
              infoList.data.status !== 2 &&
              infoList.data.status !== 18
            "
            @click="copyPurchOrder()"
            >拷贝</el-button
          >
        </template>
        <div class="model-panel">
          <div class="model-panel-title">
            <p>{{ $t('basic_information') }}</p>
          </div>
          <div class="model-panel-body">
            <basic-information :info="infoList">
              <template v-slot:basic-applicationNo>
                <div class="flex_wrap_start_start">
                  <div
                    v-if="$permission('purchOrder:detail')"
                    class="detail_item_text slip-edit"
                    @click="showPurchAppDetail(infoList.data)"
                  >
                    {{ infoList.data.applicationNo }}
                  </div>
                  <div v-else class="detail_item_text slip-edit">
                    {{ infoList.data.applicationNo }}
                  </div>
                </div>
              </template>
              <template v-slot:basic-mergedOrders>
                <span
                  v-if="
                    infoList.data.mergedOrders &&
                    infoList.data.mergedOrders.length <= 3
                  "
                >
                  <span
                    v-for="(item, itemIndex) in infoList.data.mergedOrders"
                    :key="itemIndex"
                  >
                    <a class="slip-edit" @click="getNew(item.id)">{{
                      item.orderNo
                    }}</a>
                    <span
                      v-if="itemIndex < infoList.data.mergedOrders.length - 1"
                      >,</span
                    >
                  </span>
                </span>
                <span
                  v-if="
                    infoList.data.mergedOrders &&
                    infoList.data.mergedOrders.length > 3
                  "
                >
                  <span
                    v-for="(
                      item, itemIndex
                    ) in infoList.data.mergedOrders.slice(0, 2)"
                    :key="itemIndex"
                  >
                    <a class="slip-edit" @click="getNew(item.id)">{{
                      item.orderNo
                    }}</a>
                    <span v-if="itemIndex < 1">,</span>
                  </span>
                  <el-dropdown @command="handleCommand">
                    <span class="el-dropdown-link slip-edit">
                      更多<i class="el-icon-arrow-down el-icon--right"></i>
                    </span>
                    <template #dropdown>
                      <el-dropdown-menu>
                        <el-dropdown-item
                          v-for="(
                            item, index
                          ) in infoList.data.mergedOrders.slice(
                            2,
                            infoList.data.mergedOrders.length
                          )"
                          :key="index"
                          :command="item.id"
                          >{{ item.orderNo }}
                        </el-dropdown-item>
                      </el-dropdown-menu>
                    </template>
                  </el-dropdown>
                </span>
              </template>
              <template v-slot:basic-mergedOrder>
                <a
                  v-if="infoList.data.mergeOrder"
                  class="slip-edit"
                  @click="getOld(infoList.data.mergeOrder.id)"
                  >{{ infoList.data.mergeOrder.orderNo }}</a
                >
              </template>
              <template v-slot:basic-quoteContractNos>
                <span v-if="infoList.data.purchAccording === 2">
                  {{ infoList.data.quoteContractNos }}
                </span>
              </template>
            </basic-information>
          </div>
        </div>

        <div class="model-panel">
          <div class="model-panel-title">
            <Tooltip :text="$t('detailInfo')"></Tooltip>
            <div class="model-tips">
              (证照：<span>近效期</span>
              <span class="model-tips-nearly"></span>
            </div>
            <div class="model-tips">
              <span>过期</span>
              <span class="model-tips-expire"></span>)
            </div>
            <el-button
              style="margin-left: auto; margin-right: 10px"
              @click="preferenceInfo.visible = true"
              >偏好设置</el-button
            >
          </div>
          <div class="model-panel-body">
            <div class="flex_full_item">
              <!-- 表格 -->
              <page-table
                :refresh="tableInfo.refresh"
                :init-curpage="tableInfo.initCurpage"
                v-model:data="tableInfo.data"
                :api="tableInfo.api"
                :pager="false"
                :summary="true"
                :summary-field-list="tableInfo.summaryFieldList"
                :check-box="false"
                :tab-index="true"
                :query="filterInfo.query"
                :field-list="tableInfo.fieldList"
                :handle="tableInfo.handle"
                :row-class-name="tableRowClassName"
                :isDynamic="true"
                @sortChange="sortChange"
              >
              </page-table>
            </div>
          </div>
        </div>
      </NewFullScreen>
    </div>
    <purch-application-detail
      v-if="purchAppDetailinfo.visible"
      v-model:visible="purchAppDetailinfo.visible"
      :table-row="purchAppDetailinfo.data"
    />
    <purch-application-summary-detail
      v-if="summaryDetailInfo.visible"
      v-model:visible="summaryDetailInfo.visible"
      :table-row="summaryDetailInfo.data"
      @returnBack="getList"
    />
    <purch-order-modify
      v-if="modifyInfo.visible"
      v-model:visible="modifyInfo.visible"
      :title="modifyInfo.title"
      :tableKey="modifyInfo.tableKey"
      :orderId="modifyInfo.orderId"
      :purchAccording="infoList.data.purchAccording"
      :is-copy="modifyInfo.isCopy"
      @returnModify="returnModify"
    />
    <TemplateModify
      v-if="templateModifyInfo.visible"
      v-model:visible="templateModifyInfo.visible"
      :purchOrderId="templateModifyInfo.purchOrderId"
      :title="templateModifyInfo.title"
    />
    <SetPreferenceNoQuery
      v-if="preferenceInfo.visible"
      v-model:visible="preferenceInfo.visible"
      :searchList="filterInfo.searchList"
      :fieldList="tableInfo.fieldList"
      :customizeUserVO="filterInfo.query.customizeUserVO"
      :groupLevelShow="false"
      :tableKey="tableKey"
      @callback="setPreferenceCallback"
    />
  </div>
</template>

<!-- <script>
import detailPageViewMixin from '@/mixins/detailPageViewMixin'
export default {
  mixins: [detailPageViewMixin],
}
</script> -->

<script setup name="purchOrderDetailView">
import {
  purchOrdersDetailCustomizeListAll,
  purchOrderById,
  methodPurchOrder,
  exportPurch,
  getPurchOrderPrint,
  bandQuantityHighValidateDoPurch,
  bandQuantityHighValidateSubmit,
  ordersSubmitValidatePlanRemind
} from '@/api/purch'
import { orderAffairAll } from '@/api/affair'
import { getBusinessKeyById } from '@/api/flowable'
import { getCoreSystemConfigGetConfigValue } from '@/api/core'
import { getCustomizeSetting, updateUserCustomize } from '@/api/customize'
import { fatchTemplateByCode } from '@/api/base'
import PurchApplicationDetail from '../application/detail'
import PurchOrderModify from './modify'
import PurchApplicationSummaryDetail from '@/views/purch/applicationSummary/detail'
import _ from 'lodash'
import { doPrint } from '@/utils/exportUtil.js'
import { selectByCodeAndDept } from '@/api/report.js'
import { updatePrintCount } from '@/api/mapping'
const TemplateModify = defineAsyncComponent(() => import('../template/modify'))
const SetPreferenceNoQuery = defineAsyncComponent(() =>
  import('@/components/SetPreference/setPreferenceNoQuery')
)
const emits = defineEmits()
const { proxy } = getCurrentInstance()
const props = defineProps(['visible', 'orderId', 'id'])

const tableKey = ref(
  'purchOrderDetail-com.slip.spd.entity.vo.purch.PurchOrderDetailVO'
)
const infoList = ref({
  data: {},
  fieldList: [
    { label: '采购单号', value: 'orderNo', type: 'text' },
    { label: '申购单号', value: 'applicationNo', type: 'slot' },
    { label: '供应商', value: 'supplierName', type: 'text' },
    { label: '部门', value: 'deptName', type: 'text' },
    { label: '收货联系人', value: 'receiveContacts', type: 'text' },
    { label: '收货电话', value: 'receivePhone', type: 'text' },
    { label: '收货地址', value: 'receiveAddressValue', type: 'popover' },
    { label: '状态', value: 'statusValue', type: 'text' },
    { label: '创建人', value: 'createUserName', type: 'text' },
    { label: '创建时间', value: 'createTime', type: 'text' },
    { label: '采购人', value: 'purchUserName', type: 'text' },
    { label: '采购时间', value: 'purchTime', type: 'text' },
    { label: '最后收货时间', value: 'lastReceiveTime', type: 'text' },
    { label: '最后入库时间', value: 'lastStoreTime', type: 'text' },
    { label: '新订单号', value: 'mergedOrder', type: 'slot' },
    { label: '原订单号', value: 'mergedOrders', type: 'slot' },
    { label: '采购依据', value: 'purchAccordingValue', type: 'text' },
    {
      label: '是否寄售业务',
      value: 'isConsignBusinessValue',
      type: 'text',
      show: proxy.$store.state.permission.systemConfig.is_consign_business == 1,
    },
    { label: '审批人', value: 'checkUserName', type: 'text' },
    { label: '审批意见', value: 'checkOpt', type: 'text' },
    { label: '是否临采', value: 'temporaryPurchValue', type: 'text' },
    { label: '是否紧急', value: 'isEmergencyValue', type: 'text' },
    { label: '备注', value: 'remark', type: 'text' },
  ],
})
// 过滤相关配置
const filterInfo = ref({
  sortArr: [],
  copyQueryMap: {},
  query: {
    queryMap: {
      orderId: {
        queryType: 'EQUALS',
        queryCategory: 'AND',
        value: null,
      },
    },
    queryParams: {},
  },
  searchList: [],
  searchBtn: [],
  btnList: [],
})
//另存为模板参数
const templateModifyInfo = ref({
  visible: false,
  purchOrderId: '',
  title: '另存为模板',
})
const purchAppDetailinfo = ref({
  visible: false,
  title: '申购单明细',
  data: {},
})
const summaryDetailInfo = ref({
  visible: false,
  title: '申购单汇总明细',
  data: {},
})
// 表格相关
const tableInfo = ref({
  api: undefined,
  summaryFieldList: [
    { value: 'qty', formatter: proxy.$fn.qtyFormatter },
    { value: 'sumAmount', formatter: proxy.$fn.TripartiteMethod },
  ],
  fieldList: [],
  refresh: 1,
  initCurpage: 1,
  data: [],
  selections: [],
})
const affairTableInfo = ref({
  api: orderAffairAll,
  query: {
    orderType: 'purch_order',
    orderId: props.id || props.orderId,
    sort: 'operate_time desc',
  },
})
const modifyInfo = ref({
  visible: false,
  title: '',
  orderId: '',
  tableKey: '',
  isCopy: false,
})
const preferenceInfo = ref({
  visible: false,
})
const systemConfig = ref('')
const showDialog = computed({
  get() {
    return props.visible
  },
  set(newValue) {
    emits('update:visible', newValue) // 更新父组件shows
  },
})
const canPrint = computed(() => {
  return (
    proxy.$permission('purchOrder:print') && infoList.value.data.status !== 1
  )
})
const canExcel = computed(() => {
  return (
    proxy.$permission('purchOrder:excel') && infoList.value.data.status !== 1
  )
})
//拆单
const canSplit = computed(() => {
  return (
    proxy.$permission('purchOrder:split') &&
    (infoList.value.data.status === 1 ||
      infoList.value.data.status === 2 ||
      infoList.value.data.status === 3) &&
    infoList.value.data.mergedOrders.length > 0 &&
    infoList.value.data.status === infoList.value.data.beforeMergeStatus
  )
})
const canDoPurch = computed(() => {
  return (
    (proxy.$permission('purchOrder:doPurch') &&
      infoList.value.data.status === 3) ||
    (infoList.value.data.status === 6 &&
      proxy.$store.state.permission.systemConfig.allow_purch_order_approval ==
        1)
  )
})
const canSubmit = computed(() => {
  return (
    proxy.$permission('purchOrder:submit') &&
    (infoList.value.data.status === 1 || infoList.value.data.status === 5)
  )
})
// 批准
const canRatify = computed(() => {
  return (
    proxy.$permission('purchOrder:ratify') &&
    infoList.value.data.status === 2 &&
    proxy.$store.state.permission.systemConfig.allow_purch_order_approval == 1
  )
})
// 拒绝
const canRefuse = computed(() => {
  return (
    proxy.$permission('purchOrder:refuse') &&
    infoList.value.data.status === 2 &&
    proxy.$store.state.permission.systemConfig.allow_purch_order_approval == 1
  )
})
// 驳回
const canReject = computed(() => {
  return (
    proxy.$permission('purchOrder:reject') &&
    infoList.value.data.status === 2 &&
    proxy.$store.state.permission.systemConfig.allow_purch_order_approval == 1
  )
})
const canRevoke = computed(() => {
  return (
    proxy.$permission('purchOrder:revoke') &&
    (infoList.value.data.status === 2 ||
      (infoList.value.data.status === 3 &&
        proxy.$store.state.permission.systemConfig.allow_purch_order_approval ==
          0))
  )
})
const canCancelAudit = computed(() => {
  return (
    proxy.$permission('purchOrder:cancelAudit') &&
    infoList.value.data.status === 3 &&
    proxy.$store.state.permission.systemConfig.allow_purch_order_approval !== 0
  )
})

const canBreak = computed(() => {
  return (
    proxy.$permission('purchOrder:stop') &&
    ((infoList.value.data.status === 3 &&
      proxy.$store.state.permission.systemConfig.allow_purch_order_approval !==
        0) ||
      infoList.value.data.status === 13 ||
      infoList.value.data.status === 14)
  )
})

setData()
function setData() {
  let obj = {
    price: {
      label: '单价',
      value: 'price',
      type: 'column',
      formatter: proxy.$fn.TripartiteMethod,
      permission: !proxy.$permission('purchOrder:price'),
      hidden: true,
    },
    orderNo: {
      label: '单号',
      value: 'orderNo',
      componentType: 'input',
      show: false,
      type: 'column',
      hidden: true,
    },
    sumAmount: {
      label: '总金额',
      value: 'sumAmount',
      type: 'column',
      formatter: proxy.$fn.TripartiteMethod,
      permission: !proxy.$permission('purchOrder:price'),
      hidden: true,
    },
    defaultSupplierPrice: {
      label: '默认供应商价格',
      value: 'defaultSupplierPrice',
      type: 'column',
      permission: !proxy.$permission('purchOrder:price'),
      formatter: proxy.$fn.TripartiteMethod,
      hidden: true,
    },
  }
  tableInfo.value.fieldList = Object.values({
    ...proxy.$fn.deepClone(proxy.$fieldfList.FieldList),
    ...obj,
  })
  getCustomize()
}
function sortChange(column) {
  let _filterInfo = filterInfo.value
  if (_filterInfo.query.customizeUserVO.head.sortType === 0) {
    let arr = proxy.$fn.sortChange(column, _filterInfo.sortArr)
    _filterInfo.sortArr = arr
    _filterInfo.query.sortString = arr.length ? arr.toString() : ''
    getList()
  }
}
function setPreferenceCallback(obj) {
  updateUserCustomize(obj.customizeUserVO).then((res) => {
    if (res && res.success) {
      getCustomize()
    }
  })
}
//拷贝
function copyPurchOrder() {
  modifyInfo.value.visible = true
  modifyInfo.value.isCopy = true
  modifyInfo.value.title = '拷贝采购单'
  // 显示信息
  modifyInfo.value.orderId = props.id || props.orderId
  modifyInfo.value.purchAccording = infoList.value.data.purchAccording
  if (
    infoList.value.data.purchType === 0 ||
    infoList.value.data.purchType === 1
  ) {
    modifyInfo.value.tableKey =
      'purchOrderDetailModifyByApplication-com.slip.spd.entity.vo.purch.PurchOrderDetailVO'
  } else {
    modifyInfo.value.tableKey =
      'purchOrderDetailModify-com.slip.spd.entity.vo.purch.PurchOrderDetailVO'
  }
}
//另存为模板
function saveCopeTemplate() {
  templateModifyInfo.value.visible = true
  templateModifyInfo.value.purchOrderId = props.id || props.orderId
}
function returnModify() {
  if (props.id || props.orderId) {
    getCustomize()
  }
}

//导出excel
function exportExcel() {
  exportPurch(filterInfo.value.query).then((resp) => {
    if (resp) {
      proxy.$fn.parseExcel(resp)
    }
  })
}
const templateArr = ref([])
const popoverVisible = ref(false)
//打印
function print() {
  selectByCodeAndDept({
    tempCode: 'purchOrderDetail',
    deptId: infoList.value.data.deptId,
  }).then((res) => {
    if (res && res.success) {
      templateArr.value = res.data
      popoverVisible.value = true
      // 一条数据则直接打印
      if (templateArr.value.length === 1) {
        proxy.$refs.popoverShow.hidePopover()
        doPrint({
          name: templateArr.value[0].ureportName,
          params: {
            orderId: props.id || props.orderId,
            orderNo: infoList.value.data.orderNo,
          },
          callback: printCallback,
          printCount: true,
          data: {},
        })
      }
    }
  })
}
function printCallback() {
  try {
    // 打印成功增加打印次数
    updatePrintCount({
      orderNo: infoList.value.data.orderNo,
      orderId: props.id || props.orderId,
      tempCode: 'purchOrderDetail',
      orderType: 0,
    })
  } catch (error) {}
}
function tempClick(item) {
  doPrint({
    name: item.ureportName,
    params: {
      orderId: props.id || props.orderId,
      orderNo: infoList.value.data.orderNo,
    },
    callback: printCallback,
    printCount: true,
    data: {},
  })
  popoverVisible.value = false
}
function getPirntData(temp) {
  let params = {
    tableKey:
      'purchOrderDetail-com.slip.spd.entity.vo.purch.PurchOrderDetailVO',
    orderIds: [props.id || props.orderId],
  }
  getPurchOrderPrint(params).then((res) => {
    if (res.success && res) {
      let data = proxy.$fn.deepClone(res.data)
      let newData = data.map((item) => {
        return {
          ...item,
          ...item.orderInfo,
        }
      })
      proxy.$lodop.preview(
        temp,
        newData,
        !proxy.$permission('purchOrder:price')
      )
    }
  })
}
function showPurchAppDetail(data) {
  var obj = {}
  obj.id = data.applicationId
  let purchType = data.purchType
  if (purchType === 0) {
    purchAppDetailinfo.value.visible = true
    purchAppDetailinfo.value.data = { ...obj }
  } else if (purchType === 1) {
    summaryDetailInfo.value.visible = true
    summaryDetailInfo.value.data = { ...obj }
  }
}
function getOrderInfo(orderId) {
  purchOrderById(orderId).then((resp) => {
    if (resp && resp.success) {
      infoList.value['data'] = resp.data
    }
    const item = _.find(infoList.value.fieldList, ['label', '引用合同编号'])
    if (infoList.value.data.purchAccording === 2 && !item) {
      infoList.value.fieldList.push({
        label: '引用合同编号',
        value: 'quoteContractNos',
        type: 'slot',
        className: 'not-br',
      })
    }
    tableInfo.value.fieldList.forEach((item) => {
      if (
        item.value === 'quoteContractNo' ||
        item.value === 'purchasedQty' ||
        item.value === 'purchasedAmount'
      ) {
        if (infoList.value.data.purchAccording == 2) {
          item.hidden = false
        } else {
          item.hidden = true
        }
      }
    })
  })
}
function update() {
  modifyInfo.value.visible = true
  modifyInfo.value.isCopy = false
  modifyInfo.value.title = '修改采购单'
  // 显示信息
  modifyInfo.value.orderId = props.id || props.orderId
  if (
    infoList.value.data.purchType === 0 ||
    infoList.value.data.purchType === 1
  ) {
    modifyInfo.value.tableKey =
      'purchOrderDetailModifyByApplication-com.slip.spd.entity.vo.purch.PurchOrderDetailVO'
  } else {
    modifyInfo.value.tableKey =
      'purchOrderDetailModify-com.slip.spd.entity.vo.purch.PurchOrderDetailVO'
  }
}
function handelMethodRequest(method) {
  const ids = getIds(infoList.value.data)
  if (method === 'submit') {
    ordersSubmitValidatePlanRemind(ids).then(res => {
      if(res && res.success){
        bandQuantityHighValidateSubmit(ids).then((resp) => {
          if (resp && resp.code && resp.code == 200) {
            let data = {
              flowTaskCommentDto: { approvalType: 'submit' },
              processDefinitionKey: 'purchOrder',
              orderIds: ids,
            }
            methodPurchOrder(data, method).then((resp) => {
              if (resp && resp.success) {
                getCustomize()
              }
            })
          }
        })
      }
    })
  } else if (method === 'reject') {
    proxy
      .$prompt('请输入驳回理由', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        inputValidator: proxy.$fn.maxString200,
        inputErrorMessage: '驳回理由不能超过200字符',
      })
      .then(({ value }) => {
        const data = {
          id: infoList.value.data.id,
          orderId: infoList.value.data.id,
          checkOpt: value,
        }
        methodPurchOrder(data, method).then((resp) => {
          if (resp && resp.success) {
            getCustomize()
          }
        })
      })
  } else if (method === 'refuse') {
    proxy
      .$prompt('请输入拒绝理由', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        inputValidator: proxy.$fn.maxString200,
        inputErrorMessage: '拒绝理由不能超过200字符',
      })
      .then(({ value }) => {
        const data = {
          id: infoList.value.data.id,
          orderId: infoList.value.data.id,
          checkOpt: value,
        }
        methodPurchOrder(data, method).then((resp) => {
          if (resp && resp.success) {
            getCustomize()
          }
        })
      })
  } else if (method === 'stop') {
    proxy
      .$prompt('请输入中止原因', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        inputValidator: proxy.$fn.isNotEmptyString,
        inputErrorMessage:
          '请输入中止原因并不超过200字符,存在非待发货状态且不为终结状态的发货单,不能中止',
      })
      .then(({ value }) => {
        const data = {
          ids: ids,
          stopReason: value,
        }
        methodPurchOrder(data, method).then((resp) => {
          if (resp && resp.success) {
            getOrderInfo(props.id || props.orderId)
            getList()
          }
        })
      })
  } else if (method === 'doPurch') {
    bandQuantityHighValidateDoPurch(ids).then((resp) => {
      if (resp && resp.code && resp.code == 200) {
        methodPurchOrder(ids, method).then((resp) => {
          if (resp.success) {
            getCustomize()
          }
        })
      }
    })
  } else if (method === 'approved') {
    methodPurchOrder({ orderIds: ids }, method).then((resp) => {
      if (resp.success) {
        getCustomize()
      }
    })
  } else {
    methodPurchOrder(ids, method).then((resp) => {
      if (resp.success) {
        if (
          method === 'revoke' ||
          method === 'cancelAudit' ||
          method === 'stop'
        ) {
          if (proxy.$route.query.processInstanceId) {
            proxy.$fn.setFlowPath(proxy)
            return
          }
        }
        getCustomize()
      }
    })
  }
}
function getIds(row = undefined) {
  let ids = []
  if (row) {
    ids.push(row.id)
  } else {
    ids = tableInfo.value.selections.map((row) => row.id)
  }
  return ids
}
function receiving(row) {
  proxy.$router.push({
    name: 'receivingOrder',
    params: {
      orderId: row.id,
    },
  })
}
// 触发事件
function handleEvent(event, data) {
  switch (event) {
    case 'tableCheck':
      tableInfo.value.selections = [...data]
      break
  }
}
function getOld(id){
  getBusinessKeyById({
    businessKey: infoList.value.data.mergeOrder.orderNo,
    businessType: 'purchOrder',
  }).then((res) => {
    if (res.success) {
      if (res.data?.processInstanceId) {
        proxy.$fn.setFlowData(res.data, '', proxy.$route)
      } else {
        let data = {
          urlType: 2,
          businessId: id
        }
        let url = '/purch/order'
        proxy.$router.push(url)
        proxy.$store.dispatch('settings/toPage', data)
      }
    }
  })
}
function getNew(id) {
  let row = infoList.value.data.mergedOrders.find(item => item.id===id)
  getBusinessKeyById({
    businessKey: row.orderNo,
    businessType: 'purchOrder',
  }).then((res) => {
    if (res.success) {
      if (res.data?.processInstanceId) {
        proxy.$fn.setFlowData(res.data, '', proxy.$route)
      } else {
        let data = {
          urlType: 2,
          businessId: id
        }
        let url = '/purch/order'
        proxy.$router.push(url)
        proxy.$store.dispatch('settings/toPage', data)
      }
    }
  })
}
function handleCommand(id) {
  getNew(id)
}
function getValueList() {
  getCoreSystemConfigGetConfigValue({
    systemConfigCode: 'license_nearly_effective',
  }).then((resp) => {
    if (resp && resp.success) {
      systemConfig.value = resp.data
    }
  })
}
function tableRowClassName({ row = undefined }) {
  if (row.licenseEndDate) {
    let dataDiff = proxy.$fn.dateDiffLicen(row.licenseEndDate)
    if (dataDiff <= 0) {
      return 'expire-row'
    } else if (Number(systemConfig.value) >= dataDiff) {
      return 'nearly-row'
    }
  }
  return ''
}
function getCustomize() {
  let _tableInfo = tableInfo.value
  let param = {
    tableKey: tableKey.value,
  }
  getCustomizeSetting(param).then((res) => {
    if (res && res.success) {
      let data = res.data
      _tableInfo.fieldList = proxy.$fn.setFieldList(
        _tableInfo.fieldList,
        data.detail
      )

      filterInfo.value.query.customizeUserVO = data
      filterInfo.value.query.queryMap.orderId.value = props.id || props.orderId
      _tableInfo.api = purchOrdersDetailCustomizeListAll
      getValueList()
      getOrderInfo(props.id || props.orderId)
      getList()
    }
  })
}
function returnBack() {
  emits('returnBack', false)
}
function getList() {
  purchOrdersDetailCustomizeListAll(filterInfo.value.query).then((resp) => {
    if (resp && resp.success) {
      tableInfo.value.data = resp.data
    }
  })
}
</script>
<style scoped lang="scss">
:deep(.page-table) > .el-table {
  overflow-y: hidden;
}
.model-panel-title {
  display: flex;
  align-items: center;
  .model-tips {
    display: flex;
    align-items: center;
    margin-left: 10px;
    color: #909399;
    .model-tips-nearly,
    .model-tips-expire {
      display: block;
      margin-left: 5px;
      width: 17px;
      height: 17px;
    }
    .model-tips-nearly {
      background: #fceacb;
    }
    .model-tips-expire {
      background: #f5e4e4;
    }
  }
}
:deep(.el-table) {
  .nearly-row {
    background: #fceacb;
  }
  .expire-row {
    background: #f5e4e4;
  }
}
</style>
